package kjj.android.bluetooth.app;

import java.nio.Buffer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Set;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class AndroidBluetoothActivity extends Activity implements OnClickListener{
	//debugging
	private static final String TAG = "kjj bluetooth";
	private static final boolean D = true;
	
	private static final int BUFF_SIZE = 1024;
	
	// state code
	private static final int STATE_NONE = 0;
	private static final int STATE_DISCOVERING = 1;
	
	
	//intent request code
	private static final int REQUEST_SELECT_SERVER = 1;
	
	
	//message types from the handler
	public static final int MESSAGE_NONE = 0;
	
	//intent contant strings
	public static final String EXTRA_DEVICE_LIST = "bluetooth_devices";
	
	
	//store bonded or found devices
//	private ArrayList<String> btDevicesArrayList;
	private ArrayList<String> foundBtDevices = new ArrayList<String>();
//	private ArrayList<String> pairedBtDevices = new ArrayList<String>();
	private Set<BluetoothDevice> btDevices;
	
	private BluetoothAdapter btAdapter;
	private BroadcastReceiver mReceiver = new BroadcastReceiver() {

		private StringBuffer mybuff = new StringBuffer(BUFF_SIZE);
		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			String action = intent.getAction();
			if (BluetoothDevice.ACTION_FOUND.equals(action)) {
				// a new device found
				Log.v(TAG, "onReceive()=============");

				BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
				if (device != null) {
					if (D) Log.v(TAG,"btDevices != null && device != null");
//					btDevices.add(device);
					foundBtDevices.add(device.getName() + "\n" + device.getAddress());
				}
				
				Bundle bundle = intent.getExtras();
				Object[] names = bundle.keySet().toArray();
				for (int i = 0; i < names.length; i++) {
					String keyString = names[i].toString();
					Log.v(TAG, keyString + "||" + String.valueOf(bundle.get(keyString)));
					mybuff.append(keyString+ "||" 
							+ String.valueOf(bundle.get(keyString))
							+ "\n");

				}
				mybuff.append("============\n");

			}
			else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
				Log.v(TAG, "Discover finished.");
				tView.setText(mybuff.toString());
				mybuff.setLength(0);
				//show the found devices
			}
		}
	};
	
	//UI components
	private TextView tView;
	private TextView tvSelectedBt;
	private Button btnQueryBt;
	private Button btnScanBt;
	private Button btnSelectBt;
	
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        btAdapter = BluetoothAdapter.getDefaultAdapter();
        if (btAdapter != null) {
            if (! btAdapter.isEnabled()) {
    			btAdapter.enable();    			
    			//make local bluetooth discoverable
    			Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
    			intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
//    			startActivityForResult(intent, 1);
    			
    			Toast.makeText(this, "Bluetooth is enabled.", Toast.LENGTH_SHORT)
    			.show();
    		}
		}
        else {
			Toast.makeText(this, "No Bluetooth.", Toast.LENGTH_SHORT)
			.show();
			finish();
		}
        
		tView = (TextView)findViewById(R.id.textViewInfo);
		tvSelectedBt = (TextView)findViewById(R.id.textViewSeletectedBt);
		btnQueryBt = (Button)findViewById(R.id.buttonQueryBonded);
		btnScanBt = (Button)findViewById(R.id.buttonScanBT);
		btnSelectBt = (Button)findViewById(R.id.buttonSelect);
		btnQueryBt.setOnClickListener(this);
		btnScanBt.setOnClickListener(this);
		btnSelectBt.setOnClickListener(this);
		
		//register the broadcast receiver
		IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
		registerReceiver(mReceiver, filter);
		filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
		registerReceiver(mReceiver, filter);
		
    }


	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (v == btnQueryBt) {
			btDevices = btAdapter.getBondedDevices();
			String devString;
			StringBuffer buffer = new StringBuffer();
			if (btDevices.size() > 0) {
				for (BluetoothDevice btdev : btDevices) {
					buffer.append("BtDevice Name: " + btdev.getName());
					buffer.append("\n");
					buffer.append("BtDevice Address: " + btdev.getAddress());
					buffer.append("\n");
				}
			}
			
			devString = buffer.toString();
			tView.setText(devString);
		}
		else if (v == btnScanBt) {
			//reset found devicelist
			foundBtDevices.clear();
			
			btAdapter.startDiscovery();
			tView.setText(getResources().getString(R.string.text_scanning));
		}
		else if (v == btnSelectBt) {
			//todo
			btAdapter.cancelDiscovery(); // for improving performance
			selectBtServer();
		}
	}


	private void selectBtServer() {
		// TODO Auto-generated method stub
		ArrayList<String> btDevArrayList = new ArrayList<String>();
		if (btDevices != null && btDevices.size() > 0) {
			for (BluetoothDevice btdev : btDevices) {
				btDevArrayList.add(btdev.getName() + "\n" + btdev.getAddress());
			}
		}
		
		btDevArrayList.addAll(foundBtDevices);
		Intent showDeviceIntent = new Intent(this, BluetoothDeviceListActivity.class);
		showDeviceIntent.putStringArrayListExtra(EXTRA_DEVICE_LIST, btDevArrayList);
		startActivityForResult(showDeviceIntent, REQUEST_SELECT_SERVER);
		
	}
	
	/** 
	 * process activity request
	 */
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data){
		 if(D) Log.d(TAG, "onActivityResult " + resultCode);
		 switch (requestCode) {
		case REQUEST_SELECT_SERVER:
			if (resultCode == RESULT_OK) {
				showSelectedServer(data);
			}
			break;

		default:
			break;
		}
	}


	private void showSelectedServer(Intent data) {
		// TODO Auto-generated method stub
		String nameString = 
			data.getStringExtra(BluetoothDeviceListActivity.EXTRA_BTDEVICE_NAME);
		String address = 
			data.getStringExtra(BluetoothDeviceListActivity.EXTRA_BTDEVICE_ADDRESS);
		
		tvSelectedBt.setText(nameString + "\n" + address);
		
	}
}